import os

from django.conf import settings

from apps.contents.models import ContentCategory
from apps.contents.utils import get_categories
from django.template import loader


def generate_static_index_html():
    # 标签分类
    categories = get_categories()
    # 广告数据
    contents = {}
    content_categories = ContentCategory.objects.all()
    for cat in content_categories:
        contents[cat.key] = cat.content_set.filter(status=True).order_by('sequence')
    context = {
        'categories': categories,
        'contents': contents,
    }
    # 获取首页模板文件
    template = loader.get_template("index.html")
    # 渲染 首页 html 字符串
    html_text = template.render(context)
    # 将首页静态文件写入指定目录
    file_path = os.path.join(settings.STATICFILES_DIRS[0], 'index.html')
    with open(file_path, "w", encoding='utf-8') as f:
        f.write(html_text)



